#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re
import markdown2
from bs4 import BeautifulSoup


def test_html_table_cell_merge():
    """测试HTML表格的单元格合并功能"""
    
    # 测试文件路径
    zh_file = "docs_zh/Basic Creation Guide/Getting Started/Using the Maker/Workspace/Workspace.md"
    en_file = "docs/Basic Creation Guide/Getting Started/Using the Maker/Workspace/Workspace.md"
    
    # 检查文件是否存在
    assert os.path.exists(zh_file), f"中文文件不存在: {zh_file}"
    assert os.path.exists(en_file), f"英文文件不存在: {en_file}"
    
    print("开始测试HTML表格单元格合并功能...")
    
    # 测试中文文件
    print("\n1. 测试中文文件:")
    test_file(zh_file)
    
    # 测试英文文件
    print("\n2. 测试英文文件:")
    test_file(en_file)
    
    print("\n🎉 所有单元格合并测试通过!")


def test_file(file_path):
    """测试单个文件的表格单元格合并功能"""
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 检查是否包含HTML表格
    assert '<table>' in content, f"文件中未找到HTML表格: {file_path}"
    print("✓ 包含HTML表格")
    
    # 转换为HTML并解析
    html = markdown2.markdown(content)
    soup = BeautifulSoup(html, 'html.parser')
    
    # 找到MyDesk Context Menu/MyDesk環境選單的表格
    table = None
    for h3 in soup.find_all(['h3', 'h4', 'h5', 'h6']):
        if 'MyDesk Context Menu' in h3.text or 'MyDesk環境選單' in h3.text:
            table = h3.find_next('table')
            break
    
    assert table is not None, f"未找到MyDesk相关表格: {file_path}"
    print("✓ 找到MyDesk相关表格")
    
    # 检查Create Scripts行的rowspan
    create_scripts_row = None
    import_from_row = None
    
    for row in table.find('tbody').find_all('tr'):
        cells = row.find_all('td')
        if len(cells) >= 1:
            first_cell_text = cells[0].text.strip()
            if first_cell_text == 'Create Scripts':
                create_scripts_row = row
                # 检查rowspan属性
                if 'rowspan' in cells[0].attrs:
                    rowspan_value = int(cells[0]['rowspan'])
                    print(f"✓ Create Scripts 行的 rowspan 值为: {rowspan_value}")
                    assert rowspan_value == 8, f"Create Scripts rowspan 应为 8，实际为 {rowspan_value}"
            elif first_cell_text == 'Import From':
                import_from_row = row
                # 检查rowspan属性
                if 'rowspan' in cells[0].attrs:
                    rowspan_value = int(cells[0]['rowspan'])
                    print(f"✓ Import From 行的 rowspan 值为: {rowspan_value}")
                    assert rowspan_value == 4, f"Import From rowspan 应为 4，实际为 {rowspan_value}"
    
    # 验证找到Create Scripts和Import From行
    assert create_scripts_row is not None, "未找到Create Scripts行"
    print("✓ 找到Create Scripts行")
    
    assert import_from_row is not None, "未找到Import From行"
    print("✓ 找到Import From行")
    
    # 检查表格结构完整性
    header = table.find('thead')
    assert header is not None, f"表格缺少表头: {file_path}"
    
    header_cells = header.find_all('th')
    assert len(header_cells) == 3, f"表格应该有 3 列，实际有 {len(header_cells)}"
    print("✓ 表格有 3 列")


if __name__ == "__main__":
    test_html_table_cell_merge()